package fr.ul.ade.prime.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import fr.ul.ade.R;
import fr.ul.ade.prime.analyzer.ParserQRCode;
import fr.ul.ade.prime.config.Config;
import fr.ul.ade.prime.exception.AAAException;
import fr.ul.ade.prime.exception.InvalidQrCodeException;
import fr.ul.ade.prime.model.AdeWebOptions;
import fr.ul.ade.prime.model.Project;
import fr.ul.ade.prime.model.Resource;
import fr.ul.ade.prime.qrcode.IntentIntegrator;
import fr.ul.ade.prime.qrcode.IntentResult;

/**
 * Vue affichant le formulaire de création d'un emploi du temps.
 * 
 * @author Zanette Sébastien
 * @author Andrianjafintrimo Victor
 * @author Schnell Michaël
 */
public class CreateSchedule extends AdeWebFragmentActivity {

	public static final String DATE_FORMAT_DAY = "yyyy-MM-dd"; //$NON-NLS-1$

	public static final int DEFAULT_PERIOD = 7;

	public static final SimpleDateFormat dateDecoder = new SimpleDateFormat(
			DATE_FORMAT_DAY);

	@SuppressWarnings("hiding")
	protected static final String TAG = CreateSchedule.class.getSimpleName();

	private static final int QRCODE_ID = 1;
	private static final int HELP_ID = 2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setTheme(AdeWebOptions.getTheme(this));
		this.setContentView(R.layout.create_schedule_fragment);
	}// onCreate(Bundle)

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Intent helpIntent = new Intent(this, UserManual.class);

		menu.add(Menu.NONE, QRCODE_ID, Menu.NONE, R.string.ActionBar_QRCode)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
						| MenuItem.SHOW_AS_ACTION_WITH_TEXT);

		menu.add(Menu.NONE, HELP_ID, Menu.NONE, R.string.ActionBar_help)
				.setIcon(R.drawable.ic_action_help_holo_light)
				.setIntent(helpIntent)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER
						| MenuItem.SHOW_AS_ACTION_WITH_TEXT);

		return super.onCreateOptionsMenu(menu);
	}// onCreateOptionsMenu(Menu)

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case HELP_ID:
			Intent help = new Intent(this, UserManual.class);
			this.startActivity(help);
			return true;

		case QRCODE_ID:
			IntentIntegrator integrator = new IntentIntegrator(this);
			// Personnalisation de la boite de dialogue (si l'application
			// Barcoder Scanner n'est pas installé)
			integrator.setTitleByID(R.string.Qrcode_title_dialog);
			integrator.setMessageByID(R.string.Qrcode_summary_dialog);
			integrator.setButtonYesByID(R.string.Yes);
			integrator.setButtonNoByID(R.string.No);
			// Lance l'intent Barcoder Scanner ou la boite de dialogue pour son
			// instalation
			integrator.initiateScan();
			// String urlTest =
			// "http://ade-planification.uhp-nancy.fr/jsp/custom/modules/plannings/anonymous_cal.jsp?resources=6180,6235,2815,6251,6281,7649,7786,21888,21889&projectId=5&calType=ical&firstDate=2012-07-27&lastDate=2013-08-3";

			return true;

		default:
			return true;

		}// switch
	}

	/**
	 * Calcul la différence entre les 2 dates données en paramètre, et arrondi à
	 * la plus proche valeur d'une période utilisée dans l'application
	 * 
	 * @param firstDate
	 * @param lastDate
	 * @return
	 * @throws AAAException
	 */
	private static int getPeriod(String firstDate, String lastDate) {
		try {
			Calendar ld = Calendar.getInstance();
			ld.setTime(CreateSchedule.dateDecoder.parse(lastDate));
			Calendar fd = Calendar.getInstance();
			fd.setTime(CreateSchedule.dateDecoder.parse(firstDate));
			int period = Math
					.max(0,
							ld.get(Calendar.DAY_OF_YEAR)
									- fd.get(Calendar.DAY_OF_YEAR));
			if (period > 32) {
				period = 150;
			} else if (period >= 25) {
				period = 28;
			} else if (period >= 18) {
				period = 21;
			} else if (period >= 11) {
				period = 14;
			} else {
				period = 7;
			}// if
			return period;
		} catch (ParseException e) {
			Log.d(TAG,
					String.format("Failed to parse date for period: %s", e.getMessage())); //$NON-NLS-1$
		}// try
		return DEFAULT_PERIOD;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// Récupère l'URL donnée par le QRcode via l'application de scan
		IntentResult scanResult = IntentIntegrator
				.parseActivityResult(requestCode, resultCode, intent);
		if (scanResult != null) {
			// Parse l'URL afin de récupérer les informations
			String url = scanResult.getContents();
			// L'utilisateur a annulé la scan
			if (url == null) {
				return;
			}// if
			CreateScheduleFragment fragment = (CreateScheduleFragment) this
					.getSupportFragmentManager()
					.findFragmentById(R.id.create_schedule);
			try {
				String[] resources = ParserQRCode.getResources(url)
						.split(Config.ESCAPED_RESOURCE_SEPARATOR);
				long projectId = Long.parseLong(ParserQRCode.getProjectId(url));
				int period = getPeriod(ParserQRCode.getFirstDate(url),
						ParserQRCode.getLastDate(url));
				fragment.removeEmptyResources();
				for (String res : resources) {
					fragment.addResource(res);
				}// for
				fragment.setProject(projectId);
				fragment.setPeriod(period);
			} catch (InvalidQrCodeException iqce) {
				Toast.makeText(this, R.string.QrCode_invalid_url, Toast.LENGTH_SHORT)
						.show();
			}// try
		}
		// else continue with any other code you need in the method
	}

	public void handleSave(String name, Resource[] resources, int period,
			Project project) throws AAAException {
		this.service.createSchedule(name, resources, period, project);
	}// handleSave(String, Resource[], int, Project)

}// class CreateSchedule